package com.tgy.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: tgy
 * @Date: 12/21/20 3:14 PM
 *
 * https://leetcode-cn.com/problems/3sum/
 */
public class _15_三数之和 {

    public List<List<Integer>> threeSum(int[] nums) {

        ArrayList<List<Integer>> rets = new ArrayList<>();

        if (nums == null || nums.length == 0) {

            return rets;
        }

        LinkedList<Integer> retNums = new LinkedList<>();

        Arrays.sort(nums);

        search(nums,0,rets,retNums,0);
        return rets;
    }

    private void search(int[] nums, int level,ArrayList<List<Integer>> rets, List<Integer> retNums, int sum) {

        if (retNums.size() == 3) {

            if (sum == 0) {

                rets.add(new LinkedList<>(retNums));
            }
            return;
        }

        for (int i = level; i < nums.length; i++) {

            if (i > level && nums[i - 1] == nums[i]) {
                continue;
            }
            retNums.add(nums[i]);
            search(nums,i+1,rets,retNums,sum + nums[i]);
            retNums.remove(retNums.size() - 1);
        }


    }
}
